<template>
  <cus-form style="width: 500px; margin: 0 auto;" :nodes="formGroup" :data="planInfo" ref="formRef"></cus-form>
  <div align-center>
    <el-button size="medium" @click="$refs.formRef.resetFields()">重置</el-button>
    <el-button size="medium" type="primary" :loading="saveLoading" @click="save">保存</el-button>
  </div>
</template>

<script lang="ts">
import { ref, reactive, inject } from 'vue'
import { useStore } from 'vuex'
import $ from '$';

export default {
  emits: ['basic-finally'],
  setup(props, { emit }) {

    const planInfo = inject<{ id: string }>('planInfo');

    let store = useStore();
    let formRef = ref();
    let subject = store.getters.subject;
    let userId = store.getters.userInfo.user.id;

    let formGroup = reactive([
      {
        label: '计划名称',
        key: 'planName',
        type: 'input',
        rule: { required: true, message: '请输入计划名称！' }
      },
      {
        label: '科目',
        key: 'subjectId',
        type: 'cascader',
        default: [subject.parentCode, subject.code],
        url: '/permission/user/userDataSubjects',
        valueKey: 'code',
        options: [],
        rule: { required: true, message: '请选择科目！' },
        change: (v) => getUserDataRules(v[1])
      },
      { label: '年级', type: 'select', key: 'gradeId' },
      { label: '学期', type: 'select', key: 'semesterId' },
      { label: '班型', type: 'select', key: 'courseTypeId' },
      { label: '学生层次', type: 'select', key: 'stuTypeId' }
    ]);
    $.http.post('/system/dictionary/queryDictByCodes', { typeCodesStr: 'STU_TYPE' }).then(res => formGroup[5].options = res.json.STU_TYPE);
    const getUserDataRules = async (subjectCode) => {
      formRef.value && formRef.value.resetFields(['gradeId', 'semesterId', 'courseTypeId']);
      const res = await $.http.post('/permission/user/userDataRules', { subjectCode, userId });
      formGroup[2].options = res.json.grades;
      formGroup[3].options = res.json.terms;
      formGroup[4].options = res.json.courseTypes;
    }
    getUserDataRules(subject.code);

    let [ saveLoading, setSaveLoading ] = $.useState(false);
    const save = async () => {
      let formGroup = await formRef.value.validate();
      setSaveLoading(true);
      formGroup.subjectId = typeof formGroup.subjectId === 'string' ? formGroup.subjectId : formGroup.subjectId[1];
      planInfo && (formGroup.id = planInfo.id);
      let res = await $.http.post('/admin/teachPlan/saveOrUpdate', formGroup);
      $.utils.message(res.result, `${planInfo ? '编辑' : '添加'}教学计划`);
      setSaveLoading(false);
      res.result && emit('basic-finally', res.json);
    }
    
    return { planInfo, formGroup, formRef, save, saveLoading }
  }
}
</script>